package com.edu.dk.cas.client.session;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.client.session.SessionMappingStorage;
import org.jasig.cas.client.util.AbstractConfigurationFilter;

public class SingleSignOutClusterFilter extends AbstractConfigurationFilter {
	private static final SingleSignOutClusterHandler handler = new SingleSignOutClusterHandler();

	public void init(FilterConfig filterConfig) throws ServletException {
		if (!isIgnoreInitConfiguration()) {
			handler.setArtifactParameterName(getPropertyFromInitParams(filterConfig, "artifactParameterName", "ticket"));
			handler.setLogoutParameterName(getPropertyFromInitParams(filterConfig, "logoutParameterName", "logoutRequest"));
			handler.setClusterNodes(getPropertyFromInitParams(filterConfig, "clusterNodes", null));
		}
		handler.init();
	}

	public void setArtifactParameterName(String name) {
		handler.setArtifactParameterName(name);
	}

	public void setLogoutParameterName(String name) {
		handler.setLogoutParameterName(name);
	}

	public void setSessionMappingStorage(SessionMappingStorage storage) {
		handler.setSessionMappingStorage(storage);
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		if (handler.isTokenRequest(request)) {
			// 保存token与session的映射关系
			handler.recordSession(request);
		} else if (handler.isLogoutRequest(request)) {
			// 注销请求是由cas server发出的
			handler.destroySession(request);
			return;
		} else if (handler.isLogoutRequestFromClusterNode(request)) {
			// 注销请求是由集群节点发出的
			handler.destroySessionFromClusterNode(request);
		} else {
			this.log.trace("Ignoring URI " + request.getRequestURI());
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {
	}

	protected static SingleSignOutClusterHandler getSingleSignOutHandler() {
		return handler;
	}
}
